package com.yqg.manage.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yqg.manage.entity.Laws;
import com.yqg.manage.entity.LawsAndRegulations;
import com.yqg.manage.entity.Term;
import com.yqg.manage.mapper.LawsAndRegulationsMapper;
import com.yqg.manage.service.ILawsAndRegulationsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yqg.manage.service.ILawsService;
import com.yqg.manage.service.ITermService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * LawsAndRegulationsServiceImpl 服务实现类
 *
 * @author zxf
 * @since 2025-07-26
 */
@Service
public class LawsAndRegulationsServiceImpl extends ServiceImpl<LawsAndRegulationsMapper, LawsAndRegulations> implements ILawsAndRegulationsService {
    @Resource
    private LawsAndRegulationsMapper lawsAndRegulationsMapper;
    @Resource
    private ILawsService lawsService;
    @Resource
    private ITermService termService;

    @Override
    public Map<String, Object> getLawsAndRegulationsList(Integer pageNum, Integer pageSize, String search) {
        pageNum = (pageNum - 1) * pageSize;
        Map<String,Object> map = new HashMap<>();

        System.out.println(pageNum +","+ pageSize);


        List<LawsAndRegulations> lawsAndRegulationsList = lawsAndRegulationsMapper.getLawsAndRegulationsList(pageNum,pageSize,search);
        Long count = lawsAndRegulationsMapper.getLawsAndRegulationsListCount(search);
        map.put("records",lawsAndRegulationsList);
        map.put("total",count);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean edit(LawsAndRegulations lawsAndRegulations) {
        List<Integer> illegalTermsIdList = new ArrayList<>();
        List<Integer> illegalBasisIdList = new ArrayList<>();

//        违反条款数据
        List<Term> illegalTermsObjectList = lawsAndRegulations.getIllegalTermsObject();
//        处罚依据数据
        List<Term> illegalBasisObjectList = lawsAndRegulations.getIllegalBasisObject();

//        处理法律数据
        Set<Laws> lawsSet = new HashSet<>();
        illegalTermsObjectList.forEach(ill -> {
            // 如果法律id为空，表示应该新增
            if(ill.getLawsId() == null ) {
                Laws laws = new Laws();
                laws.setName(ill.getLawName());
                laws.setType(ill.getLawType());
                lawsSet.add(laws);
            }
        });
        illegalBasisObjectList.forEach(ill ->{
            // 如果法律id为空，表示应该新增
            if(ill.getLawsId() == null ) {
                Laws laws = new Laws();
                laws.setName(ill.getLawName());
                laws.setType(ill.getLawType());
                lawsSet.add(laws);
            }
        });
        if (CollectionUtils.isNotEmpty(lawsSet)) {
            //  新增法律数据
            lawsService.saveBatch(lawsSet);
            // 建立新建法律的法律名称 -> id的映射
            Map<String,Long> lawMapping = new HashMap<>();
            lawsSet.forEach(laws -> {
                lawMapping.put(laws.getName(),laws.getId());
            });
            //  根据映射赋值
            illegalTermsObjectList.forEach(ill->{
                if (ill.getLawsId() == null) {
                    ill.setLawsId(lawMapping.get(ill.getLawName()));
                }
            });
            illegalBasisObjectList.forEach(ill->{
                if (ill.getLawsId() == null) {
                    ill.setLawsId(lawMapping.get(ill.getLawName()));
                }
            });
        }
//        处理法律条款
        Set<Term> termSet = new HashSet<>();
        illegalTermsObjectList.forEach(ill->{
            if(ill.getId() == null){
                termSet.add(ill);
            }
        });
        illegalBasisObjectList.forEach(ill->{
            if(ill.getId() == null){
                termSet.add(ill);
            }
        });
        if (CollectionUtils.isNotEmpty(termSet)) {
            //  新增法律条款数据
            termService.saveBatch(termSet);
        }
        // 建立新建法律的法律名称 -> id的映射
        Map<String,Long> termMapping = new HashMap<>();
        termSet.forEach(term -> {
            termMapping.put(termNameConcatenate(term),term.getId());
        });
        illegalTermsObjectList.forEach(ill->{
            if (ill.getId() == null) {
                illegalTermsIdList.add(termMapping.get(termNameConcatenate(ill)).intValue());
            }else {
                illegalTermsIdList.add(ill.getId().intValue());
            }
        });
        illegalBasisObjectList.forEach(ill->{
            if (ill.getId() == null) {
                illegalBasisIdList.add(termMapping.get(termNameConcatenate(ill)).intValue());
            }else {
                illegalBasisIdList.add(ill.getId().intValue());
            }
        });
        lawsAndRegulations.setIllegalTerms(illegalTermsIdList);
        lawsAndRegulations.setIllegalBasis(illegalBasisIdList);
        return saveOrUpdate(lawsAndRegulations);
    }

    /**
     * 处理条款名称拼接
     * @return 拼接的名称
     */
    public String termNameConcatenate(Term term){
        String article = term.getArticle();
        String paragraph = term.getParagraph();
        String subparagraph = term.getSubparagraph();
        String item = term.getItem();
        if (item != null) {
            return article+paragraph+subparagraph+item;
        }else if (subparagraph != null){
            return  article+paragraph+subparagraph;
        } else if (paragraph != null) {
            return  article+paragraph;
        }else {
            return  article;
        }
    }

    @Override
    public Map<String, Object> getTermObjectList(List<Integer> illegalTermsIds, List<Integer> illegalBasisIds) {
        Map<String,Object> map = new HashMap<>();
//        根据id获取数据
        Set<Integer> ids = new HashSet<>();
        ids.addAll(illegalTermsIds);
        ids.addAll(illegalBasisIds);
        List<Term> termList = lawsAndRegulationsMapper.getTermsByIds(ids);
//        建立映射
        Map<Integer, Term> termMapping = new HashMap<>();
        termList.forEach(term -> {
            termMapping.put(term.getId().intValue(), term);
        });
//        赋值
        List<Term> illegalTermsObject = new ArrayList<>();
        List<Term> illegalBasisObject = new ArrayList<>();

        illegalTermsIds.forEach( id ->{
            illegalTermsObject.add(termMapping.get(id));
        });
        illegalBasisIds.forEach( id ->{
            illegalBasisObject.add(termMapping.get(id));
        });
//        返回
        map.put("illegalTermsObject",illegalTermsObject);
        map.put("illegalBasisObject",illegalBasisObject);
        return map;
    }
}
